package com.example.auth.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.auth.common.R;
import com.example.auth.model.entity.OAuthClient;
import com.example.auth.service.OAuthClientService;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * OAuth2客户端管理控制器
 */
@RestController
@RequestMapping("/oauth/client")
public class OAuthClientController {

    @Resource
    private OAuthClientService clientService;

    /**
     * 获取客户端分页列表
     */
    @GetMapping("/page")
    @SaCheckRole("ADMIN")
    public R<Page<OAuthClient>> getClientPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String clientId,
            @RequestParam(required = false) String clientName) {
        
        Page<OAuthClient> page = new Page<>(current, size);
        LambdaQueryWrapper<OAuthClient> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (clientId != null && !clientId.isEmpty()) {
            queryWrapper.like(OAuthClient::getClientId, clientId);
        }
        if (clientName != null && !clientName.isEmpty()) {
            queryWrapper.like(OAuthClient::getClientName, clientName);
        }
        
        // 只查询未删除的记录
        queryWrapper.eq(OAuthClient::getIsDeleted, 0);
        queryWrapper.orderByDesc(OAuthClient::getCreateTime);
        
        clientService.page(page, queryWrapper);
        return R.ok(page);
    }

    /**
     * 获取客户端详情
     */
    @GetMapping("/{id}")
    @SaCheckRole("ADMIN")
    public R<OAuthClient> getClientById(@PathVariable Long id) {
        OAuthClient client = clientService.getById(id);
        return R.ok(client);
    }

    /**
     * 添加客户端
     */
    @PostMapping
    @SaCheckRole("ADMIN")
    public R<Boolean> addClient(@RequestBody OAuthClient client) {
        // 生成随机客户端ID和密钥（如果未提供）
        if (client.getClientId() == null || client.getClientId().isEmpty()) {
            client.setClientId(UUID.randomUUID().toString().replace("-", "").substring(0, 8));
        }
        if (client.getClientSecret() == null || client.getClientSecret().isEmpty()) {
            client.setClientSecret(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
        }
        
        boolean result = clientService.save(client);
        return R.ok(result);
    }

    /**
     * 更新客户端
     */
    @PutMapping
    @SaCheckRole("ADMIN")
    public R<Boolean> updateClient(@RequestBody OAuthClient client) {
        boolean result = clientService.updateById(client);
        return R.ok(result);
    }

    /**
     * 删除客户端
     */
    @DeleteMapping("/{id}")
    @SaCheckRole("ADMIN")
    public R<Boolean> deleteClient(@PathVariable Long id) {
        boolean result = clientService.removeById(id);
        return R.ok(result);
    }

    /**
     * 获取所有可用的客户端
     */
    @GetMapping("/list")
    @SaCheckRole("ADMIN")
    public R<List<OAuthClient>> getClientList() {
        LambdaQueryWrapper<OAuthClient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OAuthClient::getStatus, 1);
        queryWrapper.eq(OAuthClient::getIsDeleted, 0);
        
        List<OAuthClient> list = clientService.list(queryWrapper);
        return R.ok(list);
    }

    /**
     * 重新生成客户端密钥
     */
    @PutMapping("/regenerateSecret/{id}")
    @SaCheckRole("ADMIN")
    public R<String> regenerateClientSecret(@PathVariable Long id) {
        OAuthClient client = clientService.getById(id);
        if (client == null) {
            return R.failed("客户端不存在");
        }
        
        // 生成新的客户端密钥
        String newSecret = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        client.setClientSecret(newSecret);
        
        boolean result = clientService.updateById(client);
        if (result) {
            return R.ok(newSecret);
        } else {
            return R.failed("更新失败");
        }
    }

    /**
     * 更新客户端状态
     */
    @PutMapping("/status/{id}/{status}")
    @SaCheckRole("ADMIN")
    public R<Boolean> updateClientStatus(@PathVariable Long id, @PathVariable Integer status) {
        OAuthClient client = clientService.getById(id);
        if (client == null) {
            return R.failed("客户端不存在");
        }
        
        client.setStatus(status);
        boolean result = clientService.updateById(client);
        return R.ok(result);
    }
} 